<template>
    <div class="top-bar-box">
        <div class="top-bar-left">
            <slot name="left"></slot>
        </div>
        <div class="top-bar-right">
            <slot name="right"></slot>
            <template v-if="isLogin">
                <!-- @click="oepnSearch" -->
                <div class="search-input-box" :class="[inputFocus && 'is-focused']" ref="searchRef">
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#keowledge-sousuo"></use>
                    </svg>
                    <div class="h-line"></div>
                    <el-input ref="searchInputRef" v-model="searchVal" clearable
                        :placeholder="$t('message.placeholder.search')" @keydown.enter="searchEnter"
                        @focus="searchFocus" @blur="searchBlur"></el-input>
                    <!-- <span class="text">{{$t('message.placeholder.search')}}</span> -->
                </div>

                <el-tooltip :content="$t('message.tooltips.setting')" effect="light">
                    <i class="bar-icon knowledge-iconfont keowledge-xitongshezhi hover-back" @click="goToSetCenter()"
                        v-if="getIsGoAuth()"></i>
                </el-tooltip>
                <div class="h-line" style="margin-right: 16px;"></div>
                <div class="lang-box-item" ref="buttonRef" @click="openVisible">
                    <span>{{ currentLang.showLabel }}</span>
                    <svg class="icon">
                        <use xlink:href="#keowledge-xiala-zhankai"></use>
                    </svg>
                </div>
                <div class="header-img-box">
                    <img :src="getUserHeadImg" style="curosr:pointer;" @click="openUserInfo()">
                </div>
            </template>
            <template v-if="!isLogin">
                <el-button type="primary" @click="handleLogin">{{ $t('message.login.login') }}</el-button>
            </template>
        </div>
        <el-popover ref="popoverRef" :virtual-ref="buttonRef" trigger="click" virtual-triggering :visible="visible"
            popper-class="custom-popper-class">
            <div class="lang-list-box" v-click-outside="onClickOutsideLang">
                <el-scrollbar>
                    <div class="lang-item" v-for="(item, index) in langList" @click="changeLang(item)" :key="index">
                        <span>{{ item.label }}</span>
                        <svg class="icon" v-if="item.value === currentLang.value">
                            <use xlink:href="#keowledge-xuanzhong"></use>
                        </svg>
                    </div>
                </el-scrollbar>
            </div>
        </el-popover>
        <el-popover ref="popoverRef" :virtual-ref="searchRef" trigger="click" virtual-triggering :show-arrow="false"
            :visible="searcVisible" width="360" popper-class="custom-popper-class search-popper-class">
            <div class="history-search-box">
                <div class="lately-title">
                    <div class="title">{{ $t('message.text.recentSearch') }}</div>
                    <svg class="lately-del" @click="delHistory">
                        <use xlink:href="#keowledge-qingchulishijilu"></use>
                    </svg>
                </div>
                <div class="lately-body">
                    <template v-if="historyList.length != 0">
                        <template v-for="(item, index) in historyList">
                            <div class="lately-item" :key="index" v-if="index < 12"
                                @click="setSearchVal(item.historyName)" v-tooltip-auto-show>
                                <!-- effect="customtip" -->
                                <el-tooltip :content="item.historyName" effect="light">
                                    <span>{{ item.historyName }}</span>
                                </el-tooltip>
                            </div>
                        </template>
                    </template>
                    <jvs-empty imgSrc="@/assets/images/common/searchEmpty.png" v-if="historyList.length == 0" size="140px"
                        :text="$t('message.empty.null')" textMarginTop="0px"></jvs-empty>
                </div>
            </div>
        </el-popover>
    </div>
</template>

<script setup lang="ts">
import {
    ref,
    watch,
    onMounted,
    computed,
    getCurrentInstance,
    unref
} from 'vue'
import { ClickOutside as vClickOutside } from 'element-plus'
import userImg from '@/assets/common/user.png'
import useUserInfoStore from '@/store/userInfo';
import { getStore, setStore, removeItemAll } from "@/utils/store.js"
import { getDynamicResource } from '@/api/common'
import { useRouter, useRoute } from "vue-router"
import { permissionMatch } from '@/utils/role'
import * as O from '@/utils/uniqueId'
import useKnowledgeStore from '@/store/knowledge'
import bulletinDialog from '@/utils/bulletin.js'
// import i18n from '@/lang'
import { useHookI18n } from '@/hooks/i18n'
import useCommonStore from '@/store/common';
import indexDB from '@/utils/indexDB.js'
import { nextTick } from 'process';
const { locale, $t } = useHookI18n()
const knowStroe = useKnowledgeStore()
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const router = useRouter();
const route = useRoute()
const userStore = useUserInfoStore()
const isNewMessage = ref(false)
const isClickpop = ref(false)
const popVisible = ref(false)
const linkList = ref([])
const linkPopoverRef = ref()
const popoverSetTimer = ref()
const popoverRef = ref()
const buttonRef = ref()
const visible = ref(false)
const isLogin = computed(() => {
    return !!userStore.access_token
})
const langList = [{
    label: '中文',
    showLabel: '中',
    value: 'zh-CN'
}, {
    label: 'English',
    showLabel: 'EN',
    value: 'en'
}]
const currentLang = ref({
    label: '中文',
    showLabel: '中',
    value: 'zh-CN'
})
const searchVal = ref('')
const inputFocus = ref(false)
const searchRef = ref()
const searcVisible = ref(false)
const knowledgeDB = ref()
const historyList = ref([])
const searchInputRef = ref()
const getUserHeadImg = computed(() => {
    return userStore.userInfo.headImg ? userStore.userInfo.headImg : userImg
})
onMounted(() => {
    // let lang = getStore({name:'lang'})
    // if(!lang){
    //     const navigator = window.navigator
    //     lang = navigator.language.toLowerCase()
    // }
    indexDB.openDB('knowledgeDB', 1, knowledgeDB.value, { name: 'historyList', key: 'historyListKey' }, function (db) {
        knowledgeDB.value = db
        indexDB.readAll(db, "historyList").then(res => {
            historyList.value = res.reverse()
        })
    });
    if (route.path == '/search') {
        searchVal.value = route.query.searchText || ''
    }
    langList.forEach(item => {
        if (item.value == locale.value) {
            currentLang.value = item
        }
    })
    if (isLogin.value) {
        getDynamicResourceF()
        bulletinDialog.install()
    }
})
watch(() => route.query.searchText, () => {
    searchVal.value = route.query.searchText || ''
}, { deep: true })
function getDynamicResourceF() {
    getDynamicResource().then(res => {
        if (res.data && res.data.code == 0) {
            linkList.value = res.data.data
            setStore({ name: 'linkList', content: linkList.value })
        }
    })
}
function getIsGoAuth() {
    return permissionMatch('knowledge-control-auth') || permissionMatch('knowledge-libary-auth') || permissionMatch('knowledge-user-auth') || permissionMatch('knowledge-label-auth') ||
        permissionMatch('knowledge-static-auth') || permissionMatch('knowledge-dynamic-auth') || permissionMatch('knowledge-plugins-auth') || permissionMatch('knowledge-message-auth') ||
        permissionMatch('knowledge-messagelogs-auth') || permissionMatch('knowledge-apidocument-auth')
}

function openUserInfo() {
    proxy.$userInfo({})
}

function goToSetCenter() {
    router.push({
        path: '/setting/control'
    })
}
function handleLogin() {
    router.push({
        path: "/login",
        query: {
            redict_url: encodeURIComponent(route.fullPath)
        }
    })
}
function onClickOutsideLang() {
    visible.value = false
}
function openVisible() {
    visible.value = true
}
function changeLang(item) {
    currentLang.value = item
    locale.value = item.value
    commonStore.setLang(item.value)
    // location.reload()
    visible.value = false
}
function searchFocus() {
    inputFocus.value = true
    searcVisible.value = true
}
function searchBlur() {
    inputFocus.value = false
    searcVisible.value = false
}
function delHistory() {
    proxy.$confirm($t('message.confirm.clearHistory'), $t('message.clear'), {
        confirmButtonText: $t('message.buttons.submit'),
        cancelButtonText: $t('message.buttons.cancal'),
        type: 'warning'
    }).then(() => {
        indexDB.clearData(knowledgeDB.value, "historyList", function () {
            historyList.value = []
        })
    })
}
function searchEnter() {
    addHistry()
    searchBlur()
    setSearchVal(searchVal.value)
    searchInputRef.value.blur()
}
interface historyList {
    historyName: String,
    historyListKey: String | Number
}
function addHistry() {
    let isRe = true
    historyList.value.forEach((item: historyList) => {
        if (searchVal.value == item.historyName) {
            isRe = false
        }
    })
    if (isRe && searchVal.value) {
        indexDB.addData(
            knowledgeDB.value,
            "historyList",
            {
                historyListKey: new Date().getTime(),
                historyName: searchVal.value
            },
            function () {
                indexDB.readAll(knowledgeDB.value, "historyList").then(res => {
                    historyList.value = res.reverse()
                })
            }
        );
    }
}
function setSearchVal(val) {
    searchVal.value = val
    router.push({
        path: '/search',
        query: {
            searchText: val
        }
    })
    // searchVal.value = ''
}
</script>
<style lang="scss" scoped>
.top-bar-box {
    width: 100%;
    background: #fff;
    height: 68px;
    padding: 16px 24px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .top-bar-right {
        display: flex;
        align-items: center;

        .search-input-box {
            background-color: #F5F6F7;
            border-radius: 4px;
            height: 36px;
            width: 360px;
            display: flex;
            align-items: center;
            cursor: pointer;
            margin-right: 2px;

            .icon {
                width: 14px;
                height: 14px;
                margin: 0px 14px;
            }

            .h-line {
                height: 14px;
                background-color: #d7d8db;
                width: 1px;
                margin-left: 0px;
                margin-right: 0px;
            }

            .text {
                margin-left: 14px;
                font-size: 14px;
                color: #6f7588;
                @include SourceHanSansCN-Regular;
            }

            ::v-deep(.el-input) {
                .el-input__wrapper {
                    background-color: transparent;
                    box-shadow: none;
                }
            }
        }

        .is-focused {
            box-shadow: 0 0 0 1px #1E6FFF inset !important;
        }

        .h-line {
            background-color: #f0f1f2;
            height: 24px;
            width: 1px;
            margin-left: 24px;
            margin-right: 24px;
        }

        .bar-icon {
            // width: 21px;
            height: 32px;
            cursor: pointer;
            margin-left: 16px;
            font-size: 21px;
            color: #6F7588;
            display: flex;
            align-items: center;

            &:hover {
                color: #1D6BF5;
            }

            &:nth-of-type(1) {
                margin-left: 0px !important;
            }
        }

        .lang-box-item {
            cursor: pointer;
            width: max-content;

            span {
                font-size: 16px;
                color: #6f7588;
                @include SourceHanSansCN-Bold;
            }

            .icon {
                width: 14px;
                height: 14px;
                margin-left: 2px;
            }
        }

        .hover-back {
            margin-left: 9px;
        }

        .active {
            color: #1D6BF5;
        }

        .header-img-box {
            width: 36px;
            height: 36px;
            border-radius: 6px;
            overflow: hidden;
            margin-left: 17px;

            img {
                width: 100%;
                cursor: pointer;
                font-size: 16px;
            }
        }
    }
}

.sys-list-box {
    padding: 24px;
    box-sizing: border-box;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    column-gap: 24px;
    row-gap: 24px;

    .link-item {
        width: 88px;
        height: 88px;
        background: #F5F6F7;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        cursor: pointer;

        &:hover {
            background-color: #EEEFF0;
        }

        .sys-icon {
            width: 32px;
            height: 32px;
        }

        .sys-name {
            margin-top: 3px;
            font-size: 14px;
            @include SourceHanSansCN-Regular;
            color: #363b4c;
        }
    }
}
</style>
<style lang="scss">
.link-popover {
    padding: 0px !important;
}

.lang-list-box {
    max-height: 200px;
    padding: 8px 0px;

    .lang-item {
        padding: 0px 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
        height: 36px;

        &:hover {
            background-color: #F5F6F7 !important;
        }

        .icon {
            width: 16px;
            height: 16px;
        }
    }
}

.search-popper-class {
    transform: translateY(-10px);

    .history-search-box {
        padding: 16px 24px;

        .lately-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 14px;
            color: #363B4C;
            @include SourceHanSansCN-Bold;

            .title {
                font-size: 14px;
                color: #363B4C;
                @include SourceHanSansCN-Bold;
            }

            .lately-del {
                width: 16px;
                height: 16px;
                cursor: pointer;
            }
        }

        .lately-body {
            padding-top: 16px;
            display: flex;
            flex-wrap: wrap;
            grid-row-gap: 16px;
            grid-column-gap: 16px;

            .lately-item {
                height: 28px;
                line-height: 28px;
                background: #F5F6F7;
                border-radius: 4px;
                color: #363B4C;
                font-size: 14px;
                @include SourceHanSansCN-Regular;
                min-width: 80px;
                max-width: 155px;
                overflow: hidden;
                display: inline-block;
                text-overflow: ellipsis;
                white-space: pre;
                text-align: center;
                cursor: pointer;
                padding: 0px 8px;
                box-sizing: border-box;

                &:hover {
                    background: #EEEFF0;
                }
            }
        }
    }
}
</style>